<?php

namespace MillionMile\FormatJoinData;

class FormatJoinData
{
    /**
     * @param array $data 主数据集，以它为循环体
     * @param array $joinData 要进行关联的数据集，需要起别名
     * @param array $join 主数据集和关联数据集间的关联字段联系，必须确保字段对应
     * @param array $field 最终输出的数据集所包含的字段
     * @return array
     */
    public static function formatJoinData(array $data, array $joinData, array $join, array $field)
    {
        $joinDataRelation = [];
        foreach ($join as $mainKey => $joinKey) {
            list($joinDataName, $joinDataKey) = explode('.', $joinKey);
            $joinDataRelation[$joinDataName] = [
                'mainKey' => $mainKey,
                'joinKey' => $joinDataKey
            ];
        }

        $fieldArr = [];
        foreach ($field as $fieldItem) {
            if (strpos($fieldItem, '.') === false) {
                $fieldArr[] = $fieldItem;
            } else {
                list($dataName, $dataField) = explode('.', $fieldItem);
                $fieldArr[$dataName][] = $dataField;
            }
        }

        foreach ($joinData as $joinDataName => $joinDataItem) {
            $joinData[$joinDataName] = array_column($joinDataItem, null, $joinDataRelation[$joinDataName]['joinKey']);
        }

        $finalData = [];
        foreach ($data as $item) {
            $finalDataItem = [];
            foreach ($fieldArr as $joinDataName => $fieldItem) {
                //如果是数字，代表是主的
                if (is_string($fieldItem)) {
                    $finalDataItem[$fieldItem] = $item[$fieldItem];
                } else {
                    foreach ($fieldItem as $key) {
                        $mainKey = $joinDataRelation[$joinDataName]['mainKey'];
                        $finalDataItem[$key] = $joinData[$joinDataName][$item[$mainKey]][$key];
                    }
                }
            }
            $finalData[] = $finalDataItem;
        }
        return $finalData;
    }
}